package com.innerchic.weqiuqiu.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;

import com.innerchic.annotations.base.ActivitySetting;
import com.innerchic.annotations.base.BindActivityLayoutHolder;
import com.innerchic.mapper.app.SuperActivity;
import com.innerchic.mapper.tool.IntentFactory;
import com.innerchic.mapper.tool.SystemTool;
import com.innerchic.sponsor.other.Subject;
import com.innerchic.weqiuqiu.R;
import com.innerchic.weqiuqiu.bean.ServiceStatus;
import com.innerchic.weqiuqiu.service.MessageCoreService;
import com.innerchic.weqiuqiu.service.QiuQiuService;
import com.innerchic.weqiuqiu.utils.NotificationUtils;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：wedudu
 * 日    期：2022/1/13 9:50
 * 包    名：com.innerchic.weqiuqiu.ui
 * 描    述：主容器Activity
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */
@BindActivityLayoutHolder
@ActivitySetting(layout = "activity_content", modificationActionBar = false, observer = true, backTows = true, textTheme = true)
public class ContentActivity extends SuperActivity implements CompoundButton.OnCheckedChangeListener {

    private ContentActivityLayoutHolder holder;

    @Override
    public void create() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setTitle(Html.fromHtml("<font color='#000'>开源球球</font>"));
        }

        //检查状态
        cutService(MessageCoreService.isStartService());

        //设置泡泡开启监听
        holder.openQiuQiu.setOnCheckedChangeListener(this);
        holder.openQiuQiuSetting.setOnClickListener(v -> {
            holder.openQiuQiu.setChecked(!holder.openQiuQiu.isChecked());
        });

        //操作手册
        holder.shouceSetting.setOnClickListener(v -> {
            Intent intent = new Intent(this, TextActivity.class);
            intent.putExtra("page_title", "操作手册");
            intent.putExtra("content_text_info", getOperationManual());
            intent.putExtra("is_format_html", true);
            startActivity(intent);
        });

        //功能设置
        holder.gongnengSetting.setOnClickListener(v -> {
            Intent intent = new Intent(this, FunctionSettingActivity.class);
            startActivity(intent);
        });

        //检查权限
        holder.quanxianSetting.setOnClickListener(v -> {
            Intent intent = new Intent(this, CheckPermissionsActivity.class);
            startActivity(intent);
        });

        //问题反馈
        holder.wentiSetting.setOnClickListener(v -> {
            showToast("请通过微信或者QQ联系我...");
        });

        //Github
        holder.githubOpen.setOnClickListener(v -> {
            SystemTool.copyClipboard(this, "https://github.com/jy231613/wedudu");
            try {
                Uri uri = Uri.parse("https://github.com/jy231613/wedudu");
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.setData(uri);
                startActivity(intent);
            } catch (Exception e) {
                showToast("连接已复制,浏览器打开异常,请手动打开浏览器.");
            }
        });

        //Gitee
        holder.giteeOpen.setOnClickListener(v -> {
            SystemTool.copyClipboard(this, "https://gitee.com/JutsFx/wedudu/tree/master");
            try {
                Uri uri = Uri.parse("https://gitee.com/JutsFx/wedudu/tree/master");
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.setData(uri);
                startActivity(intent);
            } catch (Exception e) {
                showToast("连接已复制,浏览器打开异常,请手动打开浏览器.");
            }
        });

        //发送邮箱
        holder.byMyEmail.setOnClickListener(v -> {
            SystemTool.copyClipboard(this, "accterch@163.com");
            showToast("邮箱已复制");
        });

        //WeChat
        holder.byMyWeChat.setOnClickListener(v -> {
            SystemTool.copyClipboard(this, "jy271613");
            showToast("微信号已复制");
            try {
                startActivity(IntentFactory.getWxUiSkipIntent(".ui.LauncherUI"));
            } catch (Exception e) {
                showToast("跳转微信失败,微信号已复制,请手动打开微信搜索.");
            }
        });

        //QQ
        holder.byMyQQ.setOnClickListener(v -> {
            SystemTool.copyClipboard(this, "2757525207");
            try {
                String url = "mqqwpa://im/chat?chat_type=wpa&uin=2757525207";
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            } catch (Exception e) {
                showToast("请检查是否存在QQ");
            }
        });

        //启动服务
        QiuQiuService.startQiuQiuService(this, "ContentActivity");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //初始化设置
        SharedPreferences system_config_all = getSharedPreferences("system_config_all", 0);
        boolean is_open_qiuqiu = system_config_all.getBoolean("is_open_qiuqiu", false);
        holder.openQiuQiu.setChecked(is_open_qiuqiu);
        //检查权限
        checkPermissions();
        //检查功能开启个数
        checkFunction();
    }

    private void checkFunction() {
        int index = 0;
        SharedPreferences function_status = getSharedPreferences("function_status", 0);
        boolean wechat_status = function_status.getBoolean("wechat_status", true);
        if (wechat_status) {
            index++;
        }
        boolean qq_status = function_status.getBoolean("qq_status", false);
        if (qq_status) {
            index++;
        }
        boolean dingding_status = function_status.getBoolean("dingding_status", false);
        if (dingding_status) {
            index++;
        }

        boolean other_status = function_status.getBoolean("other_status", false);
        if (other_status) {
            index++;
        }
        String writes = "已开启" + index + "项";
        holder.gongnengOpenNumber.setText(writes);
    }

    /**
     * 检查权限
     */
    private int checkPermissions() {
        int index = 0;
        if (!CheckPermissionsActivity.isHasAndroidAuto(this)) {
            index++;
        }
        boolean listenersEnabled = NotificationUtils.isNotificationListenersEnabled(this);
        if (!listenersEnabled) {
            index++;
        }
        if (CheckPermissionsActivity.isNotHaveSuspensionWindow(this)) {
            index++;
        }
        if (!CheckPermissionsActivity.isIgnoringBatteryOptimizations(this)) {
            index++;
        }
        if (!CheckPermissionsActivity.isHaveSelfStarting(this)) {
            index++;
        }
        String writes = index + "项未开启";
        if (index == 0) {
            holder.quanxianOpenResult.setText("已开启");
        } else {
            holder.quanxianOpenResult.setText(Html.fromHtml("<font color='red'>" + writes + "</font>"));
        }
        return index;
    }

    @Subject(thread = Subject.THREAD_MAIN)
    private void onServiceStatus(ServiceStatus serviceStatus) {
        boolean serviceIsOpen = serviceStatus.isServiceIsOpen();
        cutService(serviceIsOpen);
    }

    private void cutService(boolean serviceIsOpen) {
        if (serviceIsOpen) {
            holder.isOpenServiceText
                    .setText("已开启");
            holder.isOpenServiceText.setTextColor(getResources().getColor(R.color.icon_green));
        } else {
            holder.isOpenServiceText
                    .setText("未开启");
            holder.isOpenServiceText.setTextColor(getResources().getColor(R.color.icon_rad));
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.content_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_kefu) {
            showToast("Please contact me via wechat or QQ ...");
        } else if (item.getItemId() == R.id.action_config) {
            Intent intent = new Intent(this, ConfigActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            //开启
            int notHave = checkPermissions();
            if (notHave == 0) {
                //启用球球
                getSharedPreferences("system_config_all", 0).edit().putBoolean("is_open_qiuqiu", true).apply();
            } else {
                showToast("您有权限未授予,请先检查权限后在开启...");
                buttonView.setChecked(false);
            }
        } else {
            //关闭
            getSharedPreferences("system_config_all", 0).edit().putBoolean("is_open_qiuqiu", false).apply();
        }
    }

    /**
     * 操作手册内容
     */
    private String getOperationManual() {
        //<font color='#6200EE'></font>
        return "1. 开始使用之前请前往<font color='#6200EE'>检查权限</font>页面检查是否开启了需要的权限,全部开启之后可以完整体验全部功能,如果后需不需要可以同样从此页面关闭.<br/>" +
                "2. <font color='#6200EE'>功能设置</font>中默认开启<font color='#6200EE'>微信</font>项,如果不需要可以在此页面关闭,也可以在当前页面开启其他项.<br/>" +
                "3. 使用之前需要使用到AndroidAuto插件,如果手机中不存在,请在<font color='#6200EE'>检查权限</font>中安装后使用.<br/>" +
                "4. 最新的代码被上传到了Gitee(码云)中,点击主页的<font color='#6200EE'>Gitee(码云)</font>可以跳转到项目主页,<font color='rad'>欢迎Star</font>.<br/>" +
                "5. 气泡操作相关,<font color='#6200EE'>点击</font>气泡可以回复消息,目前只有微信支持消息回复(文本和微信小表情).<font color='#6200EE'>右划</font>气泡可以移除当前的泡泡,<font color='#6200EE'>左滑</font>消息泡泡移除当前主页相关的所有泡泡.<br/>" +
                "6. <font color='#6200EE'>点击</font>消息体可以弹出消息回复窗,您可以输入任意文本以及小表情进行回复.<br/>" +
                "7. <font color='#6200EE'>长按</font>消息泡泡可以前往当前消息主页.<br/>" +
                "8. 您可以在<font color='#6200EE'>功能设置</font>中进行个性化设置.<br/>" +
                "9. 如有问题,可以通过<font color='#6200EE'>邮件/微信/QQ</font>联系我(*￣︶￣).<br/>";
    }
}
